<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="类型" prop="type">
          <dict v-model="queryParams.type" code="debt_type" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <dict v-model="queryParams.status" code="debt_status" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['stock:stockDebt:add']" type="success" @click="handleOpenDialog()">
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['stock:stockDebt:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        :header-cell-style="{ 'text-align': 'center' }"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          v-if="false"
          key="id"
          label="主键"
          prop="id"
          min-width="150"
          align="center"
        />
        <el-table-column label="类型" width="100" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.type" code="debt_type" />
          </template>
        </el-table-column>
        <el-table-column key="subject" label="主体" prop="subject" min-width="150" align="center" />
        <el-table-column
          key="amount"
          label="总贷款金额"
          prop="amount"
          min-width="100"
          align="right"
          :formatter="(row, column) => rounding(row, column, 2)"
        />
        <el-table-column
          key="unsettled"
          label="未结清"
          prop="unsettled"
          min-width="100"
          align="right"
          :formatter="(row, column) => rounding(row, column, 2)"
        />
        <el-table-column
          key="arrivalDate"
          label="资金到账日期"
          prop="arrivalDate"
          min-width="120"
          align="center"
        />
        <el-table-column
          key="fate"
          label="年化利率"
          prop="fate"
          min-width="100"
          align="right"
          :formatter="(row, column) => rounding(row, column, 3)"
        />
        <el-table-column
          key="fee"
          label="利息"
          prop="fee"
          min-width="100"
          align="right"
          :formatter="(row, column) => rounding(row, column, 2)"
        />
        <el-table-column
          key="startDate"
          label="还款开始月份"
          prop="startDate"
          min-width="120"
          align="center"
        />
        <el-table-column
          key="endDate"
          label="还款结束月份"
          prop="endDate"
          min-width="120"
          align="center"
        />
        <el-table-column
          key="dueDate"
          label="每月还款日"
          prop="dueDate"
          min-width="120"
          align="center"
        />
        <el-table-column label="状态" min-width="120" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.status" code="debt_status" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="250">
          <template #default="scope">
            <el-button
              v-hasPerm="['stock:stockDebt:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['stock:stockDebt:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenBillTableDialog(scope.row)"
            >
              <template #icon><Tickets /></template>
              账单
            </el-button>
            <el-button
              v-hasPerm="['stock:stockDebt:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 负债管理表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-input v-model="formData.id" type="hidden" />
        <el-form-item label="类型" prop="type">
          <dict v-model="formData.type" code="debt_type" />
        </el-form-item>
        <el-form-item label="主体" prop="subject">
          <el-input v-model="formData.subject" placeholder="主体" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="formData.amount"
            class="!w-[240px]"
            :precision="2"
            placeholder="金额"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="到账日期" prop="arrivalDate">
          <el-date-picker
            v-model="formData.arrivalDate"
            class="!w-[240px]"
            type="date"
            placeholder="到账日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="年化利率" prop="fate">
          <el-input-number
            v-model="formData.fate"
            class="!w-[240px]"
            :precision="3"
            placeholder="1.000"
          >
            <template #suffix>
              <span>%</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="利息" prop="fee">
          <el-input-number
            v-model="formData.fee"
            class="!w-[240px]"
            :precision="2"
            placeholder="利息"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="还款开始月份" prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            class="!w-[240px]"
            type="month"
            placeholder="还款开始月份"
            value-format="YYYY-MM"
          />
        </el-form-item>

        <el-form-item label="还款结束月份" prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            class="!w-[240px]"
            type="month"
            placeholder="还款结束月份"
            value-format="YYYY-MM"
          />
        </el-form-item>

        <el-form-item label="每月还款日" prop="dueDate">
          <el-input-number
            v-model="formData.dueDate"
            class="!w-[240px]"
            :precision="0"
            :min="1"
            :max="31"
          >
            <template #prefix>
              <span>每月</span>
            </template>
            <template #suffix>
              <span>号</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <dict v-model="formData.status" class="!w-[240px]" code="debt_status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 账单列表表单弹窗 -->
    <el-dialog
      v-model="billTableDialog.visible"
      :title="billTableDialog.title"
      width="800px"
      @close="handleCloseBillTableDialog"
    >
      <div class="search-bar">
        <el-form ref="billQueryFormRef" :model="billQueryParams" :inline="true">
          <el-form-item label="状态" prop="status">
            <dict v-model="billQueryParams.status" code="debt_status" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleBillQuery()">
              <template #icon><Search /></template>
              搜索
            </el-button>
            <el-button @click="handleResetBillQuery">
              <template #icon><Refresh /></template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never">
        <div class="mb-10px">
          <el-button
            v-hasPerm="['stock:stockBill:add']"
            type="success"
            @click="handleOpenBillEditDialog()"
          >
            <template #icon><Plus /></template>
            新增
          </el-button>
          <el-button
            v-hasPerm="['stock:stockBill:delete']"
            type="danger"
            :disabled="billRemoveIds.length === 0"
            @click="handleBillDelete()"
          >
            <template #icon><Delete /></template>
            删除
          </el-button>
        </div>

        <el-table
          ref="billDataTableRef"
          v-loading="billLoading"
          :data="billPageData"
          highlight-current-row
          border
          @selection-change="handleBillSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            v-if="false"
            key="id"
            label="主键"
            prop="id"
            min-width="150"
            align="center"
          />
          <el-table-column
            key="billDate"
            label="还款日期"
            prop="billDate"
            min-width="150"
            align="center"
          />
          <el-table-column
            key="billAmount"
            label="还款金额"
            prop="billAmount"
            min-width="150"
            align="center"
          />
          <el-table-column label="状态" width="150" align="center">
            <template #default="scope">
              <DictLabel v-model="scope.row.status" code="debt_status" />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="220">
            <template #default="scope">
              <el-button
                v-hasPerm="['stock:stockBill:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenBillEditDialog(scope.row.id)"
              >
                <template #icon><Edit /></template>
                编辑
              </el-button>
              <el-button
                v-hasPerm="['stock:stockBill:delete']"
                type="danger"
                size="small"
                link
                @click="handleBillDelete(scope.row.id)"
              >
                <template #icon><Delete /></template>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="total > 0"
          v-model:total="billTotal"
          v-model:page="billQueryParams.pageNum"
          v-model:limit="billQueryParams.pageSize"
          @pagination="handleBillQuery()"
        />
      </el-card>
    </el-dialog>

    <el-dialog
      v-model="billEditDialog.visible"
      :title="billEditDialog.title"
      width="500px"
      @close="handleCloseBillEditDialog"
    >
      <el-form ref="billDataFormRef" :model="billFormData" :rules="billRules" label-width="100px">
        <el-input v-model="billFormData.id" type="hidden" />
        <el-input v-model="billFormData.debtId" type="hidden" />
        <el-form-item label="还款日期" prop="billDate">
          <el-date-picker
            v-model="billFormData.billDate"
            class="!w-[240px]"
            type="date"
            placeholder="还款日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="还款金额" prop="billAmount">
          <el-input-number
            v-model="billFormData.billAmount"
            class="!w-[240px]"
            :precision="2"
            placeholder="还款金额"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <dict v-model="billFormData.status" class="!w-[240px]" code="debt_status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleBillSubmit()">确定</el-button>
          <el-button @click="handleCloseBillEditDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "StockDebt",
  inheritAttrs: false,
});

import StockDebtAPI, {
  StockDebtPageVO,
  StockDebtForm,
  StockDebtPageQuery,
} from "@/api/stock/stock-debt";
import StockBillAPI, {
  StockBillPageVO,
  StockBillForm,
  StockBillPageQuery,
} from "@/api/stock/stock-bill";
import { TableColumnCtx } from "element-plus";
import { status } from "nprogress";

const queryFormRef = ref(ElForm);
const billQueryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const billDataFormRef = ref(ElForm);

const loading = ref(false);
const billLoading = ref(false);
const removeIds = ref<number[]>([]);
const billRemoveIds = ref<number[]>([]);
const total = ref(0);
const billTotal = ref();

const queryParams = reactive<StockDebtPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const billQueryParams = reactive<StockBillPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 负债管理表格数据
const pageData = ref<StockDebtPageVO[]>([]);

// 账单管理表格数据
const billPageData = ref<StockBillPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 账单列表弹窗
const billTableDialog = reactive({
  title: "",
  visible: false,
});

// 账单编辑弹窗
const billEditDialog = reactive({
  title: "",
  visible: false,
});

// 负债管理表单数据
const formData = reactive<StockDebtForm>({});

// 账单表单数据
const billFormData = reactive<StockBillForm>({});

// 选择账单后临时存储负债ID
const storeDebtId = ref(0);

// 负债管理表单校验规则
const rules = reactive({
  type: [{ required: true, message: "请输入类型", trigger: "blur" }],
  subject: [{ required: true, message: "请输入主体", trigger: "blur" }],
  dueDate: [{ required: true, message: "请输入每月还款日", trigger: "blur" }],
  status: [{ required: true, message: "请选择债务状态", trigger: "blur" }],
});

// 账单管理表单校验规则
const billRules = reactive({
  billDate: [{ required: true, message: "请选择还款日期", trigger: "blur" }],
  billAmount: [{ required: true, message: "请输入还款金额", trigger: "blur" }],
  status: [{ required: true, message: "请选择账单状态", trigger: "blur" }],
});

function rounding(row: Record<string, any>, column: TableColumnCtx<any>, decimalPlaces: number) {
  const propertyValue = row[column.property];
  if (propertyValue === undefined || propertyValue === null) return (0.0).toFixed(decimalPlaces);
  return parseFloat(propertyValue).toFixed(decimalPlaces);
}

/** 查询负债管理 */
function handleQuery() {
  loading.value = true;
  StockDebtAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 查询账单管理 */
function handleBillQuery() {
  billLoading.value = true;
  billQueryParams.debtId = storeDebtId.value;
  StockBillAPI.getPage(billQueryParams)
    .then((data) => {
      billPageData.value = data.list;
      billTotal.value = data.total;
    })
    .finally(() => {
      billLoading.value = false;
    });
}

/** 重置负债管理查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 重置账单管理查询 */
function handleResetBillQuery() {
  billQueryFormRef.value!.resetFields();
  billQueryParams.pageNum = 1;
  billQueryParams.debtId = storeDebtId.value;
  handleBillQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 账单行复选框选中记录选中ID集合 */
function handleBillSelectionChange(selection: any) {
  billRemoveIds.value = selection.map((item: any) => item.id);
}

/** 打开负债管理弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改负债管理";
    StockDebtAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增负债管理";
    formData.status = "N"; /** 默认未结清 */
  }
}

/** 打开账单列表弹窗 */
function handleOpenBillTableDialog(row: Record<string, any>) {
  billTableDialog.visible = true;
  billTableDialog.title = row.subject;
  storeDebtId.value = row.id;
  billQueryParams.debtId = row.id;
  StockBillAPI.getPage(billQueryParams)
    .then((data) => {
      billPageData.value = data.list;
      billTotal.value = data.total;
    })
    .finally(() => {
      billLoading.value = false;
    });
}

/** 打开账单管理弹窗 */
function handleOpenBillEditDialog(id?: number) {
  billEditDialog.visible = true;
  billFormData.debtId = storeDebtId.value;
  if (id) {
    billEditDialog.title = "修改账单管理";
    StockBillAPI.getFormData(id).then((data) => {
      Object.assign(billFormData, data);
    });
  } else {
    billEditDialog.title = "新增账单管理";
    billFormData.status = "N"; /** 默认未结清 */
  }
}

/** 提交负债管理表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        StockDebtAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        StockDebtAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 提交账单管理表单 */
function handleBillSubmit() {
  billDataFormRef.value.validate((valid: any) => {
    if (valid) {
      billLoading.value = true;
      const id = billFormData.id;
      if (id) {
        StockBillAPI.update(id, billFormData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseBillEditDialog();
            handleResetBillQuery();
          })
          .finally(() => (billLoading.value = false));
      } else {
        StockBillAPI.add(billFormData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseBillEditDialog();
            handleResetBillQuery();
          })
          .finally(() => (billLoading.value = false));
      }
    }
  });
}

/** 关闭负债管理弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 关闭账单列表弹窗 */
function handleCloseBillTableDialog() {
  billTableDialog.visible = false;
  billQueryFormRef.value.resetFields();
  billQueryFormRef.value.clearValidate();
  storeDebtId.value = 0;
}

/** 关闭账单管理弹窗 */
function handleCloseBillEditDialog() {
  billEditDialog.visible = false;
  billDataFormRef.value.resetFields();
  billDataFormRef.value.clearValidate();
  billQueryParams.debtId = storeDebtId.value;
  billFormData.id = undefined;
}

/** 删除负债管理 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      StockDebtAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 删除账单管理 */
function handleBillDelete(id?: number) {
  const ids = [id || billRemoveIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      billLoading.value = true;
      StockBillAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetBillQuery();
        })
        .finally(() => (billLoading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  queryParams.status = "N"; /** 查询条件默认未结清 */
  handleQuery();
});
</script>
